package cn.com.org.controller.site;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.security.auth.login.LoginContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.google.gson.Gson;

import cn.com.bean.Person;
import cn.com.bean.Users;
import cn.com.common.EncryptUtil;
import cn.com.common.ValidateCode;
import cn.com.common.qrcode.QRCodeUtil;
import cn.com.common.tools.SessionUtil;
import cn.com.org.controller.BaseController;
import cn.com.org.service.Common;
import cn.com.org.service.UserService;

@Controller
public class HomeController extends BaseController {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Resource(name = "redisTemplate1")
	// private ValueOperations<String,String> stringOperations;
	private ValueOperations<String, String> stringOperations;
	@Autowired
	private StringRedisTemplate redisTeme;
	// private StringRedisTemplate redisTemplate;
	@Autowired
	private RedisTemplate rredisTemplate;
	
	/////////////////////////////////////////////
	@Autowired
	private UserService userService;
	/*@Autowired 
    private Common common;*/

	@Autowired
	private HttpServletRequest request;
	
	@org.springframework.web.bind.annotation.InitBinder  
	public void InitBinder(WebDataBinder dataBinder) {  
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	    dateFormat.setLenient(false);  
	    dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
	}

	public HomeController(){
		 super();
		 System.out.println(request);
		 System.out.println("+++++++++++++++++++");
	}
	@RequestMapping(value="/login", method = RequestMethod.GET)
	public String login(Map<String, Object> mapdata,
			HttpServletResponse response) throws Exception {
		return "login";
	}

	
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST,produces ={"application/html;charset=UTF-8"})
	public String login(String loginname, String loginpwd, String loginvcode,HttpServletResponse response) {

		System.out.println(loginname+"-----"+loginpwd+"------"+loginvcode+"=========");
		String validatecode = SessionUtil.getSession(request, "validatecode");

		if ("".equals(validatecode)||!validatecode.toLowerCase().equals(loginvcode.toLowerCase())) {
			return "验证码错误！";
		}
		if (loginname == null || "".equals(loginname)) {
			return "用户名不能为空！";
		}
		if (loginpwd == null || "".equals(loginpwd)) {
			return "密码不能为空！";
		}
		Boolean valresult=userService.validateUser(loginname, loginpwd);
		if(valresult){
			common.addUserCookie(response, loginname);
			return "ok";
		}
		return "false";
	}
	@ResponseBody
	@RequestMapping(value="/register", method = RequestMethod.POST,produces ={"application/html;charset=UTF-8"})
	public String register(String registername,String registerpwd,String pwdrepeater,
			HttpServletResponse response) throws Exception {
		if(registerpwd==null||"".equals(registerpwd)){
			return "密码不能为空！";
		}
		if(registerpwd.length()<6){
			return "密码长度不能小于6位！";
		}
		if(!registerpwd.equals(pwdrepeater)){
			return "两次密码不一致！";
		}
		if(registername==null||"".equals(registername)){
			return "用户名不能为空！";
		}
		Gson gson=new Gson();
	  Users users=userService.getObject("username", registername, Users.class);
	  if(users!=null){
		  return "用户已经存，请重新填写用户名！";
	  }
	  users=new Users();
	  users.setId(UUID.randomUUID());
	  users.setUsername(registername);
	  String pwd =EncryptUtil.EncryptMd5OrSHA(registerpwd,"MD5");
	  users.setPassword(pwd);
	  System.out.println(users);
	  userService.addObject(users);
		
		return "ok";
	}

	@RequestMapping("/home")
	public String home(Map<String, Object> mapdata, HttpServletResponse response)
			throws Exception {
		
		System.out.println(request);
		System.out.println("home======================");
		System.out.println(requestBase);
		System.out.println(request==requestBase);
		System.out.println("+++++++++++++++++++++++");
		
		
		//mapdata.put("username", "zxy");
		//mapdata.put("username", validateUser().get("username"));
		mapdata.put("username",uloginName);
		System.out.println(mapdata);
		System.out.println(mapdata.get("username"));
		System.out.println("start");

		// stringOperations.set("hhh", "很快");
		System.out.println(stringOperations.get("hhh"));

		// ValueOperations<String,String> stringOperations =
		// redisTemplate.opsForValue();
		ValueOperations<String, String> stringOperations = redisTeme
				.opsForValue();

		redisTeme.expire("hhh", 100000, TimeUnit.SECONDS);
		System.out.println(stringOperations.getOperations().getExpire("hhh"));
		String rrr = stringOperations.getAndSet("EER", "YYYYY");
		System.out.println(rrr);

		System.out.println(stringOperations.get("hhh"));
		Person pp = new Person();
		pp.setAge(12);
		pp.setEmail("站点");
		pp.setName(new String("中文".getBytes("unicode"), "utf-8"));

		// mongoTemplate.insert(pp);
		List<Person> plist = mongoTemplate.findAll(Person.class);

		Person p = mongoTemplate.findOne(
				new Query(Criteria.where("name").is("小吴")), Person.class);
		// System.out.println(p.toString());
		// System.out.println(plist.get(1).getEmail());
		System.out.println("end");

		return "home";
	}

	@RequestMapping("/validateCode")
	public void getCode(HttpServletResponse response) throws IOException {

		ValidateCode vcode = new ValidateCode();
		BufferedImage buffImg = vcode.getValidateCodeImg(20, 80, 5);

		// BufferedImage buffImg = QRCodeUtil.createImage("this is a test",
		// imagepath, 300); //
		String vale = vcode.getCodeValue();
		SessionUtil.setSession(request, "validatecode", vale, 600);
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		ServletOutputStream sos = response.getOutputStream();
		ImageIO.write(buffImg, "jpeg", sos);
		sos.close();
	}

	@RequestMapping(value = "/home/upload", method = RequestMethod.GET)
	//public String fileUpload(HttpServletRequest request, Map<String, Object> map) {
	public String fileUpload(Map<String, Object> map) {	
	map.put("upkey", "upvalue");
		System.out.println("get into upload get");
		String filePath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "upload/";
		File uploadDest = new File(filePath);
		String[] fileNames = uploadDest.list();
		if (fileNames != null) {
			for (int i = 0; i < fileNames.length; i++) {
				System.out.println(fileNames[i]);
			}
		}
		return "fileupload";
	}

	@RequestMapping(value = "/home/upload", method = RequestMethod.POST)
	//public String uppload(@RequestParam("myfile1") MultipartFile[] file,HttpServletRequest request, String[] dfdfdf) {
	public String uppload(@RequestParam("myfile1") MultipartFile[] file, String[] dfdfdf) {
		System.out.println(dfdfdf);
		System.out.println(Arrays.asList(dfdfdf));
		System.out.println("get into upload post");

		System.out.println(request.getContentType());
		MultipartHttpServletRequest rrrr = (MultipartHttpServletRequest) request;
		System.out.println(rrrr);
		System.out.println(file.length);
		for (int i = 0; i < file.length; i++) {
			MultipartFile multipartFile = file[i];
			System.out.println(multipartFile.getOriginalFilename() + "-----"
					+ multipartFile.getSize());

		}
		;
		// System.out.println(rrrr.getParts().size());

		Map<String, String[]> map = request.getParameterMap();
		// System.out.println(map);
		System.out.println(request.getParameter("mydata"));
		System.out.println(request.getParameter("dfdfdf"));
		String[] hhh = request.getParameterValues("dfdfdf");
		System.out.println(Arrays.asList(hhh));
		String[] hhhyy = request.getParameterValues("AAA");
		System.out.println(hhhyy);

		/*
		 * if (!file.isEmpty()) { try { // 文件保存路径 String filePath =
		 * request.getSession().getServletContext().getRealPath("/") + "upload/"
		 * + file.getOriginalFilename(); // 转存文件 file.transferTo(new
		 * File(filePath)); } catch (Exception e) { e.printStackTrace(); } }
		 */
		return "fileupload";
	}
}
